package com.lanxin.kh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lanxin.kh.entity.KhProduct;
import com.lanxin.kh.mapper.KhProductMapper;
import com.lanxin.kh.service.IKhProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 产品服务实现类
 * </p>
 *
 * @author zyq
 * @since 2025-07-26
 */
@Service
public class KhProductServiceImpl extends ServiceImpl<KhProductMapper,KhProduct> implements IKhProductService {

    /**
     * 上传目录相对路径
     */
    private static final String UPLOAD_RELATIVE_PATH = "/WEB-INF/static/upload/kh/";

    /**
     * 添加产品（含图片处理）
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean addProduct(KhProduct khProduct, MultipartFile imgfile, HttpServletRequest request) throws Exception {
        // 处理图片上传
        if (!imgfile.isEmpty()) {
            String picturePath = handleFileUpload(imgfile, request);
            khProduct.setPicture(picturePath);
        }
        // 保存产品信息
        return save(khProduct);
    }

    /**
     * 更新产品（含图片处理）
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateProduct(KhProduct khProduct, MultipartFile imgfile, HttpServletRequest request) throws Exception {
        // 处理新图片上传（如果有）
        if (imgfile != null && !imgfile.isEmpty()) {
            // 删除旧图片（可选）
            deleteOldFile(khProduct.getOid(), request);
            // 上传新图片
            String picturePath = handleFileUpload(imgfile, request);
            khProduct.setPicture(picturePath);
        }
        // 更新产品信息
        return updateById(khProduct);
    }

    /**
     * 校验产品名称是否存在
     */
    @Override
    public boolean checkNameExists(String name, Integer oid) {
        QueryWrapper<KhProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("linkname", name);
        // 编辑时排除自身
        if (oid != null) {
            queryWrapper.ne("oid", oid);
        }
        return count(queryWrapper) > 0;
    }

    /**
     * 处理文件上传
     */
    private String handleFileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 获取上传目录绝对路径
        String uploadAbsPath = request.getServletContext().getRealPath(UPLOAD_RELATIVE_PATH);
        // 创建目录（如果不存在）
        File uploadDir = new File(uploadAbsPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String newFileName = System.currentTimeMillis() + "_" + originalFilename;
        // 保存文件
        File destFile = new File(uploadAbsPath + newFileName);
        file.transferTo(destFile);
        // 返回相对路径（前端访问用）
        return "upload/kh/" + newFileName;
    }

    /**
     * 删除旧图片文件
     */
    private void deleteOldFile(Integer oid, HttpServletRequest request) {
        KhProduct oldProduct = getById(oid);
        if (oldProduct == null || StringUtils.isEmpty(oldProduct.getPicture())) {
            return;
        }
        // 构建旧图片绝对路径
        String oldPicPath = request.getServletContext().getRealPath("/WEB-INF/static/" + oldProduct.getPicture());
        File oldFile = new File(oldPicPath);
        if (oldFile.exists()) {
            oldFile.delete();
        }
    }
}